// pages/announce/announce.js
var util = require('../../../utils/util');
var check = require('../../../utils/check.js');
var api = require('../../../config/api.js');

var app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasLogin: false,
    Administrator: false,
    userInfo: {},
    index: 0,
    content: '',
    contentLength: 0,
    picUrls: [],
    files: [],
  },

  chooseImage: function(e) {
    if (this.data.files.length >= 6) {
      util.showErrorModal('只能上传六张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        that.upload(res);
      }
    })
  },
  upload: function(res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function(res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === "success") {
          var url = _res.data.url
          that.data.picUrls.push(url)
          that.setData({
            picUrls: that.data.picUrls
          })
        }
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  DelImg(e) {
    let that = this;
    wx.showModal({
      title: '图片删除',
      content: '确定要删除这张图片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          that.data.files.splice(e.currentTarget.dataset.index, 1);
          that.data.picUrls.splice(e.currentTarget.dataset.index, 1)
          that.setData({
            files: that.data.files,
            picUrls: that.data.picUrls
          })
        }
      }
    })
  },
  
  contentInput: function(e) {
    this.setData({
      contentLength: e.detail.cursor,
      content: e.detail.value,
    });
  },
  
  submitIssue: function(e) {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let that = this;

    if (that.data.content == '') {
      util.showErrorModal('请输入发布内容');
      return false;
    }

    wx.showModal({
      title: '发布日常',
      content: '确定要发布吗？',
      cancelText: '再看看',
      confirmText: '发布',
      success: res => {
        if (res.confirm) {
          util.request(api.TimelineSubmit, {
            content: that.data.content,
            picUrls: that.data.picUrls,
            isAdmin: that.data.Administrator,
          }, 'POST').then(function(res) {
            if (res.errno === "success") {
              wx.showToast({
                title: '发布成功！',
                icon: 'success',
                duration: 2000,
                complete: function() {
                  that.setData({
                    index: 0,
                    content: '',
                    contentLength: 0,
                    picUrls: [],
                    files: []
                  });
                }
              });
            } 
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      //管理员登录
      if (app.globalData.Administrator) {
        this.setData({
          Administrator: true
        });
      }
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})